package lion.json.handlers;

import java.io.IOException;
import java.io.Writer;
import java.util.Map;

import lion.json.IJsonHandler;
import lion.json.Json;

import org.apache.commons.lang.StringUtils;

/**
 * @author lion
 * @mail hl_0074@sina.com
 * @date 2011-9-27
 */
public class MapHandler implements IJsonHandler {

	@Override
	public void handle(Object o, Writer writer) throws IOException {

		if (!(o instanceof Map)) {
			writer.write("null");
			return;
		}

		Map<?, ?> m = (Map<?, ?>) o;

		writer.write("{");
		int i = 0;
		for (Object key : m.keySet()) {
			if (StringUtils.isBlank(key.toString())) {
				continue;
			}
			if (i > 0) {
				writer.write(",");
			} else {
				i++;
			}
			writer.write("\"" + key + "\":");
			Json.toJson(m.get(key), writer);
		}
		writer.write("}");
	}
}
